<template>
  <h3>computed函数的演示</h3>
  <hr>
  <div>
    <div>员工信息:</div>
    <div class="input">姓:
      <input type="text" v-model="staff.firstName">
    </div>
    <div class="input">名:
      <input type="text" v-model="staff.lastName">
    </div>
    <div class="input">
      全名: <input type="text" v-model="staff.fullName">
    </div>
    <div class="single">简单的全名: {{singleFullName}}</div>
  </div>
  <hr>
  <p>
    注意:<br>
    1. 与vue2中的computed配置功能一致.<br>
    2. 同样有简写与完整写法,用箭头函数或普通函数均可.<br>
    3. 与method相比,计算属性会缓存,所以频繁访问时性能较好.<br>
  </p>
</template>

<script>
import { reactive, computed } from 'vue'

export default {
  setup() {
    let staff = reactive({
      firstName: '南宫',
      lastName: '无雪'
    })

    //完整写法
    staff.fullName = computed({
      get() {
        return staff.firstName + '-' + staff.lastName
      },
      set(newValue) {
        let names = newValue.split('-')
        if (names) {
          staff.firstName = names[0]
          if (names.length > 1) {
            staff.lastName = names[1]
          }
        }
      }
    })

    //简写
    let singleFullName = computed(() => {
      return staff.firstName + '-' + staff.lastName
    })

    return { staff, singleFullName }
  },
}
</script>

<style scoped>

h3 {
  text-align: center;
}

.input {
  margin-top: 5px;
}

.single {
  margin-top: 5px;
}

</style>